package com.wuwei.elearning.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.question.domain.LastRecord;
import com.wuwei.elearning.question.mapper.LastRecordMapper;
import com.wuwei.elearning.question.service.LastRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户上一次做题记录，该表用于记录用户上一次练习时练习的是哪一个科目，该表方便用户下次点击时不需要重新选择科目 服务实现类
 * </p>
 *
 * @author wuwei
 * @since 2024-03-28
 */
@Service
public class LastRecordServiceImpl extends ServiceImpl<LastRecordMapper, LastRecord> implements LastRecordService {


    @Resource
    private LastRecordMapper lastRecordMapper;


    /**
     * 当用户选择了某一个课程章节后，如果表中没有数据，则添加，如果有，则修改
     * @param record LastRecord实体类
     * @param account user表的account
     * @param selectedId 如果小于10000，则为chapter表中的id字段，如果大于10000，则为subject表的id加上10000
     * @param chapterName 章节名
     */
//    @Transactional
    @Override
    public void addOrUpdate(LastRecord record, Long account,Long selectedId, String chapterName) {
        LambdaQueryWrapper<LastRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LastRecord::getUserAccount,account);

        LastRecord lastRecord = lastRecordMapper.selectOne(queryWrapper);
        if (lastRecord==null) {//如果为空，则表示该用户第一次进入该系统，则为其创建记录
            LastRecord lastRecord1 = new LastRecord();
            lastRecord1.setSelectedId(selectedId);
            lastRecord1.setLastTime(LocalDateTime.now());
            lastRecord1.setUserAccount(account);
            lastRecord1.setChatperName(chapterName);
            lastRecordMapper.insert(lastRecord1);
        } else {
            lastRecord.setSelectedId(selectedId);
            lastRecord.setChatperName(chapterName);
            lastRecord.setLastTime(LocalDateTime.now());
            lastRecordMapper.updateById(lastRecord);
        }
    }
}
